package com.wn.ziroom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wn.utils.CookieUtils;
import com.wn.utils.JwtUtils;
import com.wn.ziroom.entity.Cleaner;
import com.wn.ziroom.entity.OrderClr;
import com.wn.ziroom.entity.User;
import com.wn.ziroom.service.CleanerService;
import com.wn.ziroom.service.OrderClrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("houseService")
public class HouseServiceController {

    OrderClrService orderClrService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    CleanerService cleanerService;

    @Autowired
    public void setOrderClrService(OrderClrService orderClrService) {
        this.orderClrService = orderClrService;
    }

    @GetMapping("/addNewHouseServiceOrder")
    public String addNewHouseServiceOrder(@RequestParam(value = "Address") String address,
                                          @RequestParam(value = "createDate") String createDate,
                                          @RequestParam(value = "lastModifyDate") String lastModifyDate,
                                          @RequestParam(value = "BookDay") String bookDay,
                                          @RequestParam(value = "areasCode") String areasCode,
                                          @RequestParam(value = "streetsCode") String streetsCode,
                                          @RequestParam(value = "state",defaultValue = "0")String state,
                                          HttpServletRequest httpServletRequest
    ) {


        System.out.println("市区代码:" + areasCode);
        System.out.println("街道代码:" + streetsCode);
        System.out.println("地址:" + address);
        System.out.println("起始时间:" + createDate);
        System.out.println("结束时间:" + lastModifyDate);
        System.out.println("预约日期" + bookDay);


        String last = lastModifyDate.substring(0, 2);
        String first = createDate.substring(0, 2);

        int lastN = Integer.parseInt(last);
        int firstN = Integer.parseInt(first);

        System.out.println("结束时间N:" + lastN);
        System.out.println("开始时间N:" + firstN);

        int temp = lastN - firstN;

        double price = 0;
        String result = null;

        if (temp == 2) {
            price = 200;
        } else if (temp == 4) {
            price = 400;
        } else if (temp == 6) {
            price = 600;
        } else if (temp == 8) {
            price = 800;
        } else result = "提交失败!请正常输入!";

        System.out.println("金额:" + price);

        //开始时间和结束时间转为Date类
        String createTimeS = bookDay + " " + createDate + ":00";
        String endTimeS = bookDay + " " + lastModifyDate + ":00";

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //最终时间参数
            Date createParse = format.parse(createTimeS);
            Date endParse = format.parse(endTimeS);

            System.out.println("date:" + createParse);
            System.out.println("date:" + endParse);


            //得到用户信息
            String token = CookieUtils.getCookie("token", httpServletRequest);
            User user = JwtUtils.verifyToken(token, User.class);

            if (true) {
                OrderClr orderClr = new OrderClr();
                orderClr.setOrderIdClr("-1");

                //test
                /*orderClr.setCusId(66);*/
                orderClr.setCusId(user.getId());

                orderClr.setClrId(-1);
                orderClr.setAreasId(areasCode);
                orderClr.setStreetsId(streetsCode);
                orderClr.setAddress(address);
                orderClr.setStarttime(createParse);
                orderClr.setEndtime(endParse);
                orderClr.setDuration(temp + "");
                orderClr.setPrices(price);
                orderClr.setCreatetime(new Date());
                orderClr.setUpdatetime(new Date());
                orderClr.setState(state);

                orderClrService.save(orderClr);

                //自动分配
                autoDispatch(orderClr.getId().toString());

                return "ok";
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
        result = "请联系管理员!";

        return result;
    }

    @Transactional
    public String autoDispatch(String id) {
        QueryWrapper<OrderClr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        OrderClr orderClr = orderClrService.getOne(queryWrapper);
        if (orderClr != null) {
            if (orderClr.getState().equals("0")) {
                Date starttime1 = orderClr.getStarttime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String starttime = simpleDateFormat.format(starttime1);
                System.out.println(starttime);

                String duration = orderClr.getDuration();
                System.out.println(duration);

                String areasId = orderClr.getAreasId();
                System.out.println(areasId);

                String streetsId = orderClr.getStreetsId();
                System.out.println(streetsId);

                String bookDay = starttime.substring(0, starttime.indexOf(" "));

                System.out.println("bookDay:" + bookDay);

                System.out.println("starttime:" + starttime);
                String start = starttime.substring(starttime.indexOf(" ") + 1);
                String startCus = start.substring(0, start.indexOf(":"));

                //创建一个不可用清洁员队列备用返回值队列
                HashSet<String> DisabledTeam = new HashSet<String>();


                //用户的开始时间
                System.out.println(startCus);

                int endCus = Integer.parseInt(startCus) + Integer.parseInt(duration);

                Integer[] startTimeSpan = {8, 10, 12, 14};
                Integer[] timeLength = {2, 4, 6, 8};

                for (int i = 0; i < startTimeSpan.length; i++) {

                    //开始时间小于等于用户的服务开始时间
                    if (startTimeSpan[i] <= Integer.parseInt(startCus)) {

                        for (int j = 0; j < timeLength.length; j++) {

                            //结束时间大于等于用户的结束时间  ||  结束时间大于开始时间小于等于开始时间 = 结束时间只要大于用户的开始时间即可
                            if ((startTimeSpan[i] + timeLength[j]) > Integer.parseInt(startCus)) {

                                //查询redis的键
                                String key = bookDay + ":" + startTimeSpan[i] + ":" + timeLength[j];
                                String s = redisTemplate.opsForValue().get(key);
                                System.out.println("key:" + key + "\n" + "result:" + s);

                                //放入不可用清洁员队列
                                if (s != null) {

                                    String[] split = s.split(",");
                                    for (String tempS : split
                                    ) {
                                        System.out.println(tempS);
                                        DisabledTeam.add(tempS);
                                    }
                                }
                            }

                        }
                    }


                    //开始时间小于用户的服务结束时间
                    if (startTimeSpan[i] <= endCus) {

                        for (int j = 0; j < timeLength.length; j++) {

                            //结束时间大于等于用户的服务结束时间
                            if ((startTimeSpan[i] + timeLength[j]) >= endCus) {

                                //查询redis的键
                                String key = bookDay + ":" + startTimeSpan[i] + ":" + timeLength[j];
                                String s = redisTemplate.opsForValue().get(key);
                                System.out.println("key:" + key + "\n" + "result:" + s);

                                //放入不可用清洁员队列
                                if (s != null) {

                                    String[] split = s.split(",");
                                    for (String tempS : split
                                    ) {
                                        System.out.println(tempS);
                                        DisabledTeam.add(tempS);
                                    }
                                }
                            }

                        }
                    }

                    //开始时间大于等于用户的开始时间
                    if (startTimeSpan[i] >= Integer.parseInt(startCus)) {

                        for (int j = 0; j < timeLength.length; j++) {

                            //结束时间小于等于用户的结束时间
                            if ((startTimeSpan[i] + timeLength[j]) <= endCus) {

                                //查询redis的键
                                String key = bookDay + ":" + startTimeSpan[i] + ":" + timeLength[j];
                                String s = redisTemplate.opsForValue().get(key);
                                System.out.println("key:" + key + "\n" + "result:" + s);

                                //放入不可用清洁员队列
                                if (s != null) {

                                    String[] split = s.split(",");
                                    for (String tempS : split
                                    ) {
                                        System.out.println(tempS);
                                        DisabledTeam.add(tempS);
                                    }
                                }
                            }

                        }
                    }
                }

                //查询所有该地区的清洁员
                QueryWrapper<Cleaner> wrapper = new QueryWrapper<>();
                HashMap<String, String> map = new HashMap<>();
                map.put("clr_area", areasId);
                map.put("clr_street", streetsId);
                map.put("clr_state", "1");
                wrapper.allEq(map);
                List<Cleaner> list = cleanerService.list(wrapper);


                System.out.println("---------------");
                Object[] endTeam = DisabledTeam.toArray();

                System.out.println("--------------------");
                Iterator<Cleaner> iterator = list.iterator();
                System.out.println(endTeam);

                while (iterator.hasNext()) {
                    Cleaner next = iterator.next();
                    System.out.println(next);
                    for (int i = 0; i < endTeam.length; i++) {
                        if ((next.getId().toString()).equals((String) endTeam[i])) {
                            System.out.println("a:" + next.getId() + ",b:" + endTeam[i]);
                            iterator.remove();
                        }
                    }
                }

                System.out.println("-----------");
                for (Cleaner c : list
                ) {
                    System.out.println(c);
                }

                System.out.println("----------------");
                int size = list.size();

                if (size != 0) {

                    Random random = new Random();
                    Cleaner cleaner = list.get(random.nextInt(list.size()));
                    //cleaner是我们需要的清洁员-------------------------

                    String starttime2 = starttime.substring(starttime.indexOf(" ") + 1);

                    starttime2 = starttime2.substring(0, starttime2.indexOf(":"));

                    System.out.println(starttime2);

                    //得到key去查询
                    String key = bookDay + ":" + Integer.parseInt(starttime2) + ":" + Integer.parseInt(duration);
                    String s = redisTemplate.opsForValue().get(key);
                    System.out.println("key:" + key + "\n" + "result:" + s);

                    //如果redis没有则添加
                    if (s == null) {
                        redisTemplate.opsForValue().set(key, cleaner.getId() + ",");
                    } else {
                        //如果redis有的话就先删除后添加
                        s = s + cleaner.getId() + ",";
                        redisTemplate.opsForValue().getAndDelete(key);
                        redisTemplate.opsForValue().set(key, s);
                    }

                    //修改数据库

                    OrderClr orderClr2 = new OrderClr();
                    orderClr2.setId(Integer.parseInt(id));
                    orderClr2.setClrId(cleaner.getId());
                    orderClr2.setState("1");
                    boolean b = orderClrService.updateById(orderClr2);

                    System.out.println("auto,success!!!!");
                }
            }
        }
        return null;
    }


}
